package ctl.util;

import org.fusesource.jansi.Ansi.*;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiConsole;

import ctl.anno.JDBCConfig;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@JDBCConfig(database = "sqlserverdb", encoding = "UTF-8", ip = "192.168.1.191", loginName = "sa", password = "123", driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver")
public class DBUtil {

    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        JDBCConfig config = DBUtil.class.getAnnotation(JDBCConfig.class);
        String ip = config.ip();
        int port = config.port();
        String loginName = config.loginName();
        String password = config.password();
        String encoding = config.encoding();
        String database = config.database();
        String driverName = config.driverName();
        //加载驱动
        Class.forName(driverName);
        //规范格式
        String url = String.format("jdbc:sqlserver://%s:%d;?characterEncoding=%s;DataBaseName=%s", ip, port, encoding, database);
        //返回连接
        return DriverManager.getConnection(url, loginName, password);
    }

    public static void main(String[] args) {
        try {
            Connection connection = getConnection();
            System.out.println(connection);
            PreparedStatement pst = null;
            ResultSet rs = null;
            String sql = "select * from Student";
            pst = connection.prepareStatement(sql);
            rs = pst.executeQuery();
            while (rs.next()) {
                
                System.out.println(rs.getInt(1) + "\t\t\t\t\t\t" + rs.getString(2) + "\t\t\t\t\t\t" + rs.getString(3) + "\t\t\t\t\t\t"
                    + rs.getString(4));
            }
        } catch (ClassNotFoundException | SQLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }
}
